package com.cl.unipay4j.ali.splitbill;

import com.alibaba.fastjson.JSON;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.cl.unipay4j.ali.AbstractAliPay;
import com.cl.unipay4j.core.IPayConfig;
import com.cl.unipay4j.core.Result;
import com.cl.unipay4j.core.exception.InvalidParamException;
import com.cl.unipay4j.core.splitbill.ISplitBill;
import com.cl.unipay4j.core.splitbill.ProfitModel;
import com.cl.unipay4j.core.splitbill.Receiver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付宝分账
 *
 * @author siashan
 * @since v1.0.1
 **/
public class AliPaySplitBill extends AbstractAliPay implements ISplitBill {
    public AliPaySplitBill() {
    }

    public AliPaySplitBill(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 分账
     *
     * @param model  请求实体
     * @return 分账结果
     */
    @Override
    public Result split(ProfitModel model) {
        try {
            AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
            request.setBizContent(JSON.toJSONString(wrapParam(model)));
            AlipayTradeOrderSettleResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }

        } catch (Exception e) {

        }
        return Result.exception();
    }


    /**
     * 封装请求参数
     *
     * @param model 请求实体
     * @return 请求参数
     */
    private Map<String, Object> wrapParam(ProfitModel model) {
        Map<String, Object> map = new HashMap<>();
        List<Receiver> receivers = model.getReceivers();
        if (null == receivers || receivers.isEmpty()) {
            throw new InvalidParamException("分账接受方不能为空");
        }

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> royaltyMap = null;
        for (Receiver r : receivers) {
            royaltyMap = new HashMap<>();
            royaltyMap.put("royalty_type", r.getType());
            royaltyMap.put("amount", r.getAccount());
            royaltyMap.put("desc", r.getDescription());
            royaltyMap.put("trans_in", r.getAccount());
            royaltyMap.put("trans_in_type", r.getAccount());
            list.add(royaltyMap);
        }
        map.put("trade_no", model.getTradeNo());
        map.put("out_request_no", model.getOutTradeNo());
        map.put("royalty_parameters", list);
        return map;
    }
}
